package com.dcbeida.utils;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Window;
import android.widget.Toast;

import com.dcbeida.callback.PhotoCallBack;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class GetPhotoFromAlbum {

    private static File mCurrentPhotoFile;
    private static File cropfile;

    /**
     * 通过何种方式获取图片
     * PHOTO_PICKED_WITH_DATA 相册
     * CAMERA_WITH_DATA 相机
     *
     * @param way
     */
    public static void ChooseWay(Context context, int way) {
        if (CameraUtil.PHOTO_PICKED_WITH_DATA == way) {
            try {
                Intent intent = CameraUtil.getPhotoPickIntent();
                ((Activity) context).startActivityForResult(intent, CameraUtil.PHOTO_PICKED_WITH_DATA);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
            }
        }
        if (CameraUtil.CAMERA_WITH_DATA == way) {
            try {
                if (!CameraUtil.PHOTO_DIR.exists()) {
                    CameraUtil.PHOTO_DIR.mkdirs();
                }
                mCurrentPhotoFile = new File(CameraUtil.PHOTO_DIR, CameraUtil.getPhotoFileName());
                Intent intent = CameraUtil.getTakePickIntent(mCurrentPhotoFile);
                ((Activity) context).startActivityForResult(intent, CameraUtil.CAMERA_WITH_DATA);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param context
     * @param requestCode 如果是相册调用 cameraFile传null即可
     * @param cut         是否调用系统剪辑
     */
    public static void GetPhoto(Activity context, int requestCode, Intent data,
                                boolean cut, PhotoCallBack callBack) {
        //***********图库*****************//
        if (requestCode == CameraUtil.PHOTO_PICKED_WITH_DATA) {
            try {
                String imagePath = "";
                Uri uri = data.getData();
                if (uri != null) {//直接根据uri处理照片
                    getImagePathFromURI(context, uri, cut, callBack);
                } else {
                    Bundle extras = data.getExtras();
                    if (extras != null) {
                        // 这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
                        Bitmap image = extras.getParcelable("data");
                        if (image != null) {
                            imagePath = CameraUtil.savePhotoBitmap(image);
                            if (callBack != null) {
                                if (cut) {
                                    doCropPhoto(context, uri, new File(imagePath));
                                } else {
                                    Log.i("fancl", "GetPhoto:" + "2");
                                    callBack.Success(imagePath);
                                }
                            }

                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //***********照相*****************//
        if (requestCode == CameraUtil.CAMERA_WITH_DATA) {
            if (callBack != null) {
                if (cut) {
                    doCropPhoto(context, null, mCurrentPhotoFile);
                } else {
                    Log.i("fancl", "GetPhoto:" + "3");
                    callBack.Success(mCurrentPhotoFile.getAbsolutePath());
                }
            }

        }

        //***********裁剪*****************//
        if (requestCode == CameraUtil.CAMERA_COMPLETE) {
            Log.i("fancl", "GetPhoto:" + "4");
            callBack.Success(cropfile.getAbsolutePath());
        }

    }

    /**
     * 直接根据uri 获取图片
     *
     * @param context
     * @param uri
     * @param cut
     * @param callBack
     */
    public static void getImagePathFromURI(Context context, Uri uri, boolean cut, PhotoCallBack callBack) {
        Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
        cursor.moveToFirst();
        String document_id = cursor.getString(0);
        document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
        cursor.close();
        cursor = context.getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                null, MediaStore.Images.Media._ID + " = ? ",
                new String[]{document_id}, null);
        cursor.moveToFirst();
        String path = cursor.getString(cursor
                .getColumnIndex(MediaStore.Images.Media.DATA));
        cursor.close();
        if (callBack != null && !cut) {
            Log.i("fancl", "getImagePathFromURI:" + "1");
            callBack.Success(path);
        }
        if (cut) {
            doCropPhoto(context, uri, new File(path));
        }
    }

    /**
     * 裁剪调用
     *
     * @param context
     * @param uri
     * @param filePath
     */
    public static void doCropPhoto(Context context, Uri uri, File filePath) {
        try {
            Intent intent = null;
            if (uri != null) {
                intent = getCropImageIntent(uri, 1, 1, CameraUtil.CROP_WIDTH, CameraUtil.CROP_HEIGHT);
            } else {
                intent = getCropImageIntent(
                        Uri.parse("file://" + Uri.decode(filePath.getAbsolutePath())), 1,
                        1, CameraUtil.CROP_WIDTH, CameraUtil.CROP_HEIGHT);
            }
            ((Activity) context).startActivityForResult(intent, CameraUtil.CAMERA_COMPLETE);
        } catch (Exception e) {
            Toast.makeText(context, "图片获取失败", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 调用图片剪辑程序
     */
    public static Intent getCropImageIntent(Uri photoUri, int aspectX, int aspectY, int outputX, int outputY) {
        Intent intent = null;
        intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(photoUri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", aspectX);//宽高比
        intent.putExtra("aspectY", aspectY);
        intent.putExtra("outputX", outputX);
        intent.putExtra("outputY", outputY);
        intent.putExtra("scale", true);

        cropfile = new File(CameraUtil.CROP_FILE_DIR + File.separator + CameraUtil.getPhotoFileName());

        try {
            if (cropfile.exists()) {
                cropfile.delete();
            }
            cropfile.getParentFile().mkdirs();
            cropfile.createNewFile();
        } catch (IOException ex) {
            Log.e("io", ex.getMessage());
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cropfile));
        intent.putExtra("return-data", false);// 若为false则表示不返回数据
        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", false);
        intent.putExtra("circleCrop", false);
        return intent;
    }


    /**
     * 多线程压缩图片的质量
     *
     * @param imgPath 图片的保存路径
     * @author JPH
     * @date 2014-12-5下午11:30:43
     */
    public static void compressImageByQuality(final String imgPath, final Activity activity, final Handler iHandler) {
        final ProgressDialog dialog = new ProgressDialog(activity);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(false);
        dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setMessage("图片压缩中...");
        dialog.show();
        new Thread(new Runnable() {
            private File tempImgPath;

            @Override
            public void run() {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int options = 100;
                Bitmap bitmap = CameraUtil.fitSizeImg2(activity, imgPath);
                bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//质量压缩方法，把压缩后的数据存放到baos中 (100表示不压缩，0表示压缩到最小)
                while (baos.toByteArray().length / 1024 > (1 * 1024)) {//循环判断如果压缩后图片是否大于?M,大于继续压缩
                    baos.reset();//重置baos即让下一次的写入覆盖之前的内容
                    options -= 10;//图片质量每次减少10
                    Log.i("sean", "#############options##压缩图片的质量:" + options);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//将压缩后的图片保存到baos中
                    if (options < 90) {
                        break;//如果图片的质量小于80，不再进行压缩
                    }
                }
                try {
                    tempImgPath = newTempFile();
                    FileOutputStream fos = new FileOutputStream(tempImgPath);//将压缩后的图片保存的本地上指定路径中
                    fos.write(baos.toByteArray());
                    fos.flush();
                    fos.close();
                    baos.reset();
                    baos.flush();
                    baos.close();
                    bitmap.recycle();
                    bitmap = null;
                } catch (Exception e) {
                    e.printStackTrace();
                }

                Message m = new Message();
                m.what = 100;
                m.obj = tempImgPath.getAbsolutePath();
                iHandler.sendMessage(m);
                iHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                    }
                });
            }
        }).start();
    }

    /**
     * 多线程压缩图片的质量
     *
     * @param imgPath 图片的保存路径
     * @author JPH
     * @date 2014-12-5下午11:30:43
     */
    public static void compressImageByQualityList(final List<String> imgPath, final Activity activity, final Handler iHandler) {

        new Thread(new Runnable() {//开启多线程进行压缩处理
            private File tempImgPath;

            @Override
            public void run() {
                for (int i = 0; i < imgPath.size(); i++) {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int options = 100;

                    Bitmap bitmap = comp(BitmapFactory.decodeFile(imgPath.get(i)));
                    bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//质量压缩方法，把压缩后的数据存放到baos中 (100表示不压缩，0表示压缩到最小)
                    while (baos.toByteArray().length / 1024 > 1024) {//循环判断如果压缩后图片是否大于?M,大于继续压缩
                        baos.reset();//重置baos即让下一次的写入覆盖之前的内容
                        options -= 10;//图片质量每次减少10
                        if (options < 0)
                            options = 0;//如果图片质量小于10，则将图片的质量压缩到最小值
                        bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//将压缩后的图片保存到baos中
                        if (options == 0)
                            break;//如果图片的质量已降到最低则，不再进行压缩
                    }
                    try {

                        tempImgPath = newTempFile();
                        FileOutputStream fos = new FileOutputStream(tempImgPath);//将压缩后的图片保存的本地上指定路径中

                        fos.write(baos.toByteArray());
                        fos.flush();
                        fos.close();
                        baos.reset();
                        baos.flush();
                        baos.close();
                        bitmap.recycle();
                        bitmap = null;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    Message m = new Message();
                    m.what = 100;
                    m.obj = tempImgPath.getAbsolutePath();
                    iHandler.sendMessage(m);
                }

            }
        }).start();
    }

    //压缩好比例大小
    private static Bitmap comp(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        if (baos.toByteArray().length / 1024 > 1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            baos.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, baos);//这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        //现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        float hh = 800f;//这里设置高度为800f
        float ww = 480f;//这里设置宽度为480f
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;//降低图片从ARGB888到RGB565
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        return bitmap;//压缩好比例大小后再进行质量压缩
    }

    /**
     * 创建一个新的文件
     *
     * @return
     */
    public static File newTempFile() {

        String PATH = android.os.Environment.getExternalStorageDirectory().getAbsolutePath() + Constants.DEFAULT_DATA_TEMP;
        File dir = new File(PATH);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss SSS");
        String filename = MD5Util.MD5(format.format(new Date()));
        File file = new File(PATH, filename + ".jpg");
        try {
            file.createNewFile();
        } catch (IOException e) {

            e.printStackTrace();
        }
        return file;
    }

}
